package com.helpustotravel.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.helpustotravel.core.ServletBase;
import com.helpustotravel.model.dao.PhotoDAO;
import com.helpustotravel.model.dao.TravellerDAO;
import com.helpustotravel.model.jdo.Photo;
import com.helpustotravel.model.jdo.Traveller;

@SuppressWarnings("serial")
public class GetAllTravellersPhotosServlet extends ServletBase {

	public static String NAME = "GetAllTravellersPhotos";
	
	protected HttpServletResponse doTache(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		TravellerDAO travellerDao = new TravellerDAO(pm);
		List<Traveller> travellers = travellerDao.getAllTraveller();
		
		String json = "{\"travellers\":[";
		
		for(int t = 0; t < travellers.size(); t++) {
			
			Traveller traveller = travellers.get(t);
		
			json += "{\"name\":\"" + traveller.getName() +
					"\",\"completeName\":\"" + traveller.getCompleteName() + 
					"\",\"photos\":[";
			
			PhotoDAO photoDao = new PhotoDAO(pm);
			List<Photo> photos = photoDao.getPhotos(traveller.getName());
			
			int i = 0;
			
			for(Photo photo : photos) {
				
				if(photo != null) {
					json += "{\"photoUrl\":\"" + photo.getPhotoUrl() + 
							"\",\"isProfilPhoto\":\"" + photo.isProfilPhoto() +
							"\",\"filename\":\"" + photo.getFilename() + 
							"\",\"blobkey\":\"" + photo.getBlobKey() + 
							"\"}";
					
					if(i < (photos.size() - 1)) {
						json += ",";
					}
				}
				
				i++;
			}
			
			json += "]}";

			if(t < (travellers.size() - 1)) {
				json += ",";
			}
		}
		
		json += "]}";
		
		resp.getWriter().print(json);
		return resp;
	}
}
